package com.ljfiction.book.Dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ljfiction.book.MyView.ObservableHorizontalScrollView;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.Md5;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.Tool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;


public class TotouweixiaomijinjiaoDialog {

    private String bookid, bookname, authorId;
    private NoBackgLodDialog noBackgLodDialog;
    private Dialog mDialog;
    private Listener listener;
    private Context mContext;
    private ViewHolder viewHolder;
    private PhoneBangding phoneBangdingDialog;
    private boolean isScrollleft = false;

    public TotouweixiaomijinjiaoDialog(Context context, String bookid, String bookname, String authorId) {
        mContext = context;
        this.bookid = bookid;
        this.bookname = bookname;
        this.authorId = authorId;
        mDialog = new Dialog(context, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(context).inflate(R.layout.givelajiao_bookdata, null);
        viewHolder = new ViewHolder(view);
        //将布局设置给Dialog
        mDialog.setContentView(view);
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.width = context.getResources().getDisplayMetrics().widthPixels;
        view.setLayoutParams(layoutParams);
        mDialog.getWindow().setGravity(Gravity.BOTTOM);
        mDialog.getWindow().setWindowAnimations(R.style.AnimBottom);
        mDialog.setCancelable(true);
        intView();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void intView() {
        viewHolder.xiaomijiaoyue.setText("小米椒余额: " + String.valueOf(UserManageBean.userBean.getUserRecommendTicket()));
        viewHolder.xiaomijiaoyue2.setText("金椒余额: " + String.valueOf(UserManageBean.userBean.getUserGoldenTicket()));
        viewHolder.subtractGivefragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Integer.valueOf(viewHolder.textGivefragment.getText().toString()) <= 0) {
                    Tool.showToast("主人，不能再少啦！", mContext);
                } else {
                    viewHolder.textGivefragment.setText(String.valueOf(Integer.valueOf(viewHolder.textGivefragment.getText().toString()) - 1));
                }
            }
        });
        viewHolder.subtractGivefragment2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Integer.valueOf(viewHolder.textGivefragment2.getText().toString()) <= 0) {
                    Tool.showToast("主人，不能再少啦！", mContext);
                } else {
                    viewHolder.textGivefragment2.setText(String.valueOf(Integer.valueOf(viewHolder.textGivefragment2.getText().toString()) - 1));
                }
            }
        });
        viewHolder.addGivefragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Integer.valueOf(viewHolder.textGivefragment.getText().toString()) >= 10) {
                    Tool.showToast("主人，小米椒很珍贵，省着点用吧！", mContext);
                } else {
                    viewHolder.textGivefragment.setText(String.valueOf(Integer.valueOf(viewHolder.textGivefragment.getText().toString()) + 1));
                }
            }
        });
        viewHolder.addGivefragment2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Integer.valueOf(viewHolder.textGivefragment2.getText().toString()) >= 10) {
                    Tool.showToast("主人，金椒很珍贵，省着点用吧！", mContext);
                } else {
                    viewHolder.textGivefragment2.setText(String.valueOf(Integer.valueOf(viewHolder.textGivefragment2.getText().toString()) + 1));
                }
            }
        });
        viewHolder.allGivefragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!(UserManageBean.userBean.getUserRecommendTicket() >= 0)) {
                    Tool.showToast("没有小米椒了！", mContext);
                } else if (UserManageBean.userBean.getUserRecommendTicket() > 10) {
                    viewHolder.textGivefragment.setText("10");
                    Tool.showToast("主人，小米椒很珍贵，省着点用哦！", mContext);
                } else {
                    viewHolder.textGivefragment.setText(String.valueOf(UserManageBean.userBean.getUserRecommendTicket()));
                }
            }
        });
        viewHolder.allGivefragment2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!(UserManageBean.userBean.getUserGoldenTicket() >= 0)) {
                    Tool.showToast("没有金椒了！", mContext);
                } else if (UserManageBean.userBean.getUserGoldenTicket() > 10) {
                    viewHolder.textGivefragment2.setText("10");
                    Tool.showToast("主人，金椒很珍贵，省着点用哦！", mContext);
                } else {
                    viewHolder.textGivefragment2.setText(String.valueOf(UserManageBean.userBean.getUserGoldenTicket()));
                }
            }
        });
        viewHolder.feedGivefragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserManageBean.isLogin(mContext)) {
                    thisdismis();
                    return;
                }
                if (UserManageBean.userBean.getUserPhone().equals("0")) {
                    if (phoneBangdingDialog == null) {
                        phoneBangdingDialog = new PhoneBangding(mContext);
                        phoneBangdingDialog.setListener(new PhoneBangding.Listener() {
                            @Override
                            public void giveyanzhengnoLogin() {
                                listener.subnologin();
                                return;

                            }

                            @Override
                            public void setok() {
                                UserManageBean.backgroundRiches(mContext);
                            }

                            @Override
                            public void clickquhao() {

                                listener.clickquhao();
                            }
                        });
                    }
                    phoneBangdingDialog.show();

                    return;
                }
                if (Integer.valueOf(viewHolder.textGivefragment.getText().toString()) > UserManageBean.userBean.getUserRecommendTicket()) {
                    Tool.showToast("主人，小米椒不够了！", mContext);
                    return;
                } else if (Integer.valueOf(viewHolder.textGivefragment.getText().toString()) < 1) {
                    Tool.showToast("主人，请大方一点吧！", mContext);
                    return;
                }
                toTouweixmj();
            }
        });
        viewHolder.feedGivefragment2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserManageBean.isLogin(mContext)) {
                    thisdismis();
                    return;
                }
                if (Integer.valueOf(viewHolder.textGivefragment2.getText().toString()) > UserManageBean.userBean.getUserGoldenTicket()) {
                    Tool.showToast("主人，金椒不够了！", mContext);
                    return;
                } else if (Integer.valueOf(viewHolder.textGivefragment2.getText().toString()) < 1) {
                    Tool.showToast("主人，请大方一点吧！", mContext);
                    return;
                }
                toTouweijinpiao();
            }
        });
        viewHolder.huanzuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewHolder.scrollviewGive.smoothScrollTo(0, 0);
            }
        });
        viewHolder.huanyou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewHolder.scrollviewGive.smoothScrollTo(ScreenUtils.getScreenWidth(), 0);
            }
        });
        viewHolder.scrollviewGive.setHorizontalScrollViewListener(new ObservableHorizontalScrollView.HorizontalScrollViewListener() {
            @Override
            public void onScrollChanged(ObservableHorizontalScrollView HorizontalScrollView, int x, int y, int oldx, int oldy) {
                viewHolder.viewGive.setTranslationX(x / 2);
                if (x - oldx > 0) {
                    isScrollleft = true;
                } else {
                    isScrollleft = false;
                }
            }
        });

        viewHolder.scrollviewGive.setOnTouchListener(new View.OnTouchListener() {

            private int lastY = 0;
            private int touchEventId = -9983761;
            @SuppressLint("HandlerLeak")
            Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    View scroller = (View) msg.obj;

                    if (msg.what == touchEventId) {
                        if (lastY == scroller.getScrollY()) {
                            //停止了，此处你的操作业务
                            if (isScrollleft) {
                                viewHolder.scrollviewGive.smoothScrollTo(ScreenUtils.getScreenWidth(), 0);
                            } else {
                                viewHolder.scrollviewGive.smoothScrollTo(0, 0);
                            }

                        } else {
                            handler.sendMessageDelayed(handler.obtainMessage(touchEventId, scroller), 1);
                            lastY = scroller.getScrollY();
                        }
                    }
                }
            };

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int eventAction = event.getAction();
                switch (eventAction) {
                    case MotionEvent.ACTION_UP:
                        handler.sendMessageDelayed(handler.obtainMessage(touchEventId, v), 5);
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }


    public void thisdismis() {
        mDialog.dismiss();
    }

    public void show(int type) {
        if (mDialog != null) {
            mDialog.show();
            if (type==0){
                viewHolder.scrollviewGive.scrollTo(0,0);
            }else {
                viewHolder.scrollviewGive.scrollTo(ScreenUtils.getScreenWidth(),0);
            }
        }
    }
public void  setQuhao(String quhao){
        if (mDialog!=null){
            phoneBangdingDialog.setQuhao(quhao);
        }
}
    public void setListener(Listener listener) {
        this.listener = listener;
    }

    public interface Listener {
        void subclickok();

        void clickquhao();

        void subnologin();
    }

    private void toTouweixmj() {
        OkHttpUtils.post(HttpManager.IP + "/user-RecommendationTicket")
                .headers("timestr",  String.valueOf(System.currentTimeMillis()/180000) )
                .headers("sign",Md5.encryption(SettingManager.getInstance().getUUID()+"#"+android.os.Build.BRAND+"#"+android.os.Build.MODEL+"#"+Md5.encryption(SettingManager.getInstance().getUUID().substring(7,25))+"#"+String.valueOf(System.currentTimeMillis()/180000)))
                .params("recommendTicketCount", viewHolder.textGivefragment.getText().toString())
                .params("bookid", bookid)
                .params("authorId", authorId)
                .params("bookName", bookname)
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog==null){
                            noBackgLodDialog=new NoBackgLodDialog(mContext,true);
                        }
                        noBackgLodDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog!=null){
                            noBackgLodDialog.dismis();
                        }
                        try {
                            JSONObject json = new JSONObject(s);
                            if (200 == json.getInt("returnCode")) {
                                Tool.showToast(json.getString("msg"), mContext);
                                try {
                                    UserManageBean.userBean.setUserRecommendTicket(UserManageBean.userBean.getUserRecommendTicket()-Integer.valueOf(viewHolder.textGivefragment.getText().toString()));
                                } catch (NumberFormatException e) {
                                    e.printStackTrace();
                                }
                                viewHolder.xiaomijiaoyue.setText("小米椒余额: " + String.valueOf(UserManageBean.userBean.getUserRecommendTicket()));
                                listener.subclickok();
                                UserManageBean.backgroundRiches(mContext);
                                thisdismis();
                            } else {
                                if (400 == json.getInt("returnCode")) {
                                    listener.subnologin();
                                }
                                Tool.showToast(json.getString("msg"), mContext);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void toTouweijinpiao() {

        OkHttpUtils.post(HttpManager.IP + "/user-RewardGonderTicket")

                .params("goldenTicketCount", viewHolder.textGivefragment2.getText().toString())
                .params("bookid", bookid)
                .params("authorId", authorId)
                .params("bookName", bookname)
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog==null){
                            noBackgLodDialog=new NoBackgLodDialog(mContext,true);
                        }
                        noBackgLodDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog!=null){
                            noBackgLodDialog.dismis();
                        }


                        try {
                            JSONObject json = new JSONObject(s);
                            if (200 == json.getInt("returnCode")) {
                                Tool.showToast(json.getString("msg"), mContext);
                                try {
                                    UserManageBean.userBean.setUserGoldenTicket(UserManageBean.userBean.getUserGoldenTicket()-Integer.valueOf(viewHolder.textGivefragment2.getText().toString()));
                                } catch (NumberFormatException e) {
                                    e.printStackTrace();
                                }
                                viewHolder.xiaomijiaoyue2.setText("金椒余额: " + String.valueOf(UserManageBean.userBean.getUserGoldenTicket()));
                                listener.subclickok();
                                UserManageBean.backgroundRiches(mContext);
                                thisdismis();
                            } else {
                                if (400 == json.getInt("returnCode")) {
                                    listener.subnologin();
                                }
                                Tool.showToast(json.getString("msg"), mContext);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    static class ViewHolder {
        @BindView(R.id.huanzuo)
        TextView huanzuo;
        @BindView(R.id.huanyou)
        TextView huanyou;
        @BindView(R.id.view_give)
        RelativeLayout viewGive;
        @BindView(R.id.xiaomijiaoyue)
        TextView xiaomijiaoyue;
        @BindView(R.id.xiaomijiaoyue2)
        TextView xiaomijiaoyue2;
        @BindView(R.id.subtract_givefragment)
        SuperButton subtractGivefragment;
        @BindView(R.id.text_givefragment)
        SuperButton textGivefragment;
        @BindView(R.id.add_givefragment)
        SuperButton addGivefragment;
        @BindView(R.id.all_givefragment)
        SuperButton allGivefragment;
        @BindView(R.id.feed_givefragment)
        SuperButton feedGivefragment;
        @BindView(R.id.subtract_givefragment2)
        SuperButton subtractGivefragment2;
        @BindView(R.id.text_givefragment2)
        SuperButton textGivefragment2;
        @BindView(R.id.add_givefragment2)
        SuperButton addGivefragment2;
        @BindView(R.id.all_givefragment2)
        SuperButton allGivefragment2;
        @BindView(R.id.feed_givefragment2)
        SuperButton feedGivefragment2;
        @BindView(R.id.scrollview_give)
        ObservableHorizontalScrollView scrollviewGive;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
